package com.azt.service.wechat.impl;

import com.alibaba.fastjson.JSONObject;
import com.azt.model.WeChatUserInfo;
import com.azt.service.wechat.WeChatCaller;
import com.azt.service.wechat.WeChatService;
import com.azt.utils.FastjsonDecoder;
import com.google.common.base.Preconditions;
import feign.Feign;
import feign.slf4j.Slf4jLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import static com.azt.service.wechat.WeChatConstant.APP_SECRET;
import static com.azt.service.wechat.WeChatConstant.WEB_APP_ID;

/**
 * 微信处理类
 * Created by LiQZ on 2017/3/30.
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    private static final Logger logger = LoggerFactory.getLogger(WeChatServiceImpl.class);

    WeChatCaller weChatCaller = Feign.builder()
            .decoder(new FastjsonDecoder())
            .logger(new Slf4jLogger(WeChatServiceImpl.class))
            .target(WeChatCaller.class, "https://api.weixin.qq.com");

    @Override
    public WeChatUserInfo getUserInfo(String code) {
        JSONObject openInfo = weChatCaller.getAccessToken(WEB_APP_ID, APP_SECRET, code);
        logger.info("WeChat call back openInfo {}", openInfo);
        Preconditions.checkArgument(openInfo.containsKey("access_token") && openInfo.containsKey("openid"));
        String openid = openInfo.getString("openid");
        String accessToken = openInfo.getString("access_token");
        String unionId = openInfo.getString("unionid");
        JSONObject userInfo = weChatCaller.getUserInfo(accessToken, openid);
        String nickName = userInfo.getString("nickname");
        String avatar = userInfo.getString("headimgurl");
        logger.info("WeChat userinfo {}", userInfo);
        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
        weChatUserInfo.setUnionId(unionId);
        weChatUserInfo.setAvatar(avatar);
        weChatUserInfo.setNick(nickName);
        return weChatUserInfo;
    }

	@Override
	public JSONObject getAccessToken(String appId, String secret, String code) {
		return weChatCaller.getAccessToken(WEB_APP_ID, APP_SECRET, code);
	}

}
